package com.gt.sensitive;

/**
 * @author humingxuan
 * @since 2024-09-26 16:59
 */

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Field;

@Slf4j
public class SensitiveDataSerializer extends JsonSerializer<Object> {

    @Override
    public void serialize(Object entity, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        Field[] fields = entity.getClass().getDeclaredFields();
        gen.writeStartObject();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Sensitive sensitive = field.getAnnotation(Sensitive.class);
                Object fieldValue = field.get(entity);
                if (sensitive != null && fieldValue instanceof String) {
                    String maskedValue = SensitiveUtils.maskSensitiveData((String) fieldValue, sensitive.type());
                    gen.writeStringField(field.getName(), maskedValue);
                } else {
                    gen.writeObjectField(field.getName(), fieldValue);
                }
            } catch (IllegalAccessException e) {
                log.error("脱敏数据出错", e);
            }
        }
        gen.writeEndObject();
    }
}
